<template>
	<div class="cmt-container">
		<h4>发表评论</h4>
		<hr>
		<textarea placeholder="请输入要BB的内容，最多120个字" v-model="msg"></textarea >
		<mt-button type="primary" size="large" @click="postCommitInfo">发表评论</mt-button>
		<div class="cmt-list">
			<div class="cmt-item" v-for="(item,i) in commit_list " :key="i" >
				<div class="cmt-title">第{{i}}楼&nbsp;&nbsp;用户：{{item.user_name}}&nbsp;&nbsp;发表时间:{{item.add_time|dateFormat}}
				</div>
				<div class="cmt-body">
					{{item.content}}
				</div>
			</div>
			<mt-button type="danger" plain  size="large" @click="	getMore">加载更多</mt-button>
		</div>
	</div>	
		
	
</template>
<style scoped lang="scss">
	.cmt-container{
		textarea{
			margin:0px;
			font-size: 14px;
		}
		.cmt-list{
			margin-top:10px;
			.cmt-item{
				.cmt-title{
					line-height: 30px;
					background-color: gray;
					font-size: 14px;
				}
				.cmt-body{
					line-height: 35px;
					font-size: 16px;
					background-color: white;
					text-indent: 2em;
					// 缩进
				}
			}
		}

	}
	
</style>
<script>
	import { Toast } from 'mint-ui';
	export default{
		// 把获取到的数据保存到data上，方便渲染数据
		data:function(){
			return{
				pageindex:1,
				'commit_list':[],
				msg:" ",
				// id:this.artid
			};
		},

		// artid是资讯的id，我们要获取哪个资讯下面的评论，要把资讯的id传给commit组件，属于父组件传值给子组件
		props:['artid'],
		created:function(){
			this.getCommit();
		},
		methods:{
			// 获取评论数据
			getCommit:function(){
				this.$http.get('http://www.liulongbin.top:3005/api/getcomments/'+this.artid+'?pageindex='+this.pageindex).then(result=>{
					
					if(result.body.status==0)
					{
						this.commit_list = this.commit_list.concat(result.body.message);
						console.log(result.body.message);
					}
				else{
					Toast('评论数据加载失败');
				}
			});
		},
		// 加载更多
		getMore(){
			this.pageindex=this.pageindex+1;
			this.getCommit();
		},
		//提交评论
		postCommitInfo(){
			// 注意提交的评论不能为空
			console.log('msg:'+this.msg);
			if(this.msg.length===0)
			{	
				return Toast('提交评论不能为空');
			}

			this.$http.post('api/postcomment/'+this.artid,{comment:this.msg.trim()},{emulateJSON:true}).then(result =>{
				if(result.body.status==0)
				{
					
					console.log(result.body.message);
					// this.getCommit();
					// 如果已经点击加载了第二页，那么pageIndex为二，重新刷新，获取的是第二页，看不到你提交的评论
					// 手动组织一个对象，unshift在'commit_list'评论列表里面
					var Newcommit={
						user_name:'匿名用户',
						add_time:new Date(),
						content:this.msg.trim()
					};
					this.commit_list.unshift(Newcommit);
					// 清空评论
					this.msg="";

				}
				else{
					Toast("提交评论失败");
				}
			} );
		}
		}
		
	}

</script>